package com.white.crackwifi.utils;

import com.white.crackwifi.statics.ExecuteCmdEnum;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangzy
 * @Description: 本地执行工具类
 * @date 2019/12/24 14:25
 */
public class ExecuteUtil {

    private ExecuteUtil(){}

    /**
     * 执行命令
     * @param cmd 执行的命令
     * @return
     * @throws IOException
     */
    public static List<String> execute(String cmd)throws IOException{
        return execute(cmd,null);
    }

    /**
     * 执行命令
     * @param cmd 执行的命令
     * @param filePath 需要在哪个目录执行
     * @return
     * @throws IOException
     */
    public static List<String> execute(String cmd , String filePath)throws IOException{
        List<String> result = new ArrayList<>();
        Process process;
        if (filePath != null) {
            File file = new File(filePath);
            if (!file.isDirectory()){
                throw new IOException("路径不是一个目录");
            }
            process = Runtime.getRuntime().exec(cmd,null, file);
        }else {
            process = Runtime.getRuntime().exec(cmd);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
        String line = null;
        while ((line = br.readLine()) != null) {
            result.add(line);
        }
        return result;
    }

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();
    }

}
